import { ReactElement, useState, useEffect, useRef } from 'react'
import style from './index.module.less'
import Search, { formatCondition } from '@src/pages/admin/components/searchForm'
import Table, { TableRef } from '@components/table'
import { ConditionSchema } from '@src/components/schema/condition'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import { getCaseListRequest } from './ajax'
import qs from 'query-string'
import { json2Excel } from '@js/excel'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { Modal, message, Button } from 'antd'
import { formatDate } from '@js/tool'
import { useDispatch } from 'react-redux'

const { confirm } = Modal

// 初始化数据
async function initData (data: { [k: string]: any}, setDataSource: (v: CaseSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseListRequest({
    condition: formatAllCondition(data),
    page: data.page,
    limit: data.limit
  }))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
  }
}

// 格式化搜索条件
function formatAllCondition (o: { [k: string]: any }): ConditionSchema[] {
  const condition = formatCondition(o)
  return condition
}

// 下载excel二次确认
function confirmDownload (data: { [k: string]: any}, total: number): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要导出excel吗？',
    onOk () {
      downloadExcel(data, total).catch(e => console.error(e))
    }
  })
}

async function downloadExcel (data: { [k: string]: any}, total: number): Promise<void> {
  const hide = message.loading('下载中', 120)
  const [e, d] = await awaitWrap(getCaseListRequest({
    condition: formatAllCondition(data),
    page: 1,
    limit: total
  }))
  hide()
  if (e === null && d !== null) {
    const list: Array<{ [k: string]: any }> = d.list.map(li => {
      return {
        仲裁程序: li.procedure,
        办案秘书: li.processer,
        受理秘书: li.accepter,
        收案理日期: formatDate(li.accept_datetime, 'YYYY-MM-DD'),
        标的: li.dispute_amount,
        反请求标的: li.counter_dispute_amount,
        案号: li.caseno_desc,
        案由: li.cause_action,
        '独任/首席仲裁员': li.arbitrator,
        申请人: li.applicant_name,
        申请人仲裁员: li.arbitrator1,
        移交办案日期: formatDate(li.to_process_datetime, 'YYYY-MM-DD'),
        立案日期: formatDate(li.docket_datetime, 'YYYY-MM-DD'),
        组庭日期: formatDate(li.arbitrator_assign_datetime, 'YYYY-MM-DD'),
        开庭日期: formatDate(li.begin_hearing_datetime, 'YYYY-MM-DD'),
        结案方式: li.closure_type,
        结案文书报送日期: formatDate(li.closure_report_datetime, 'YYYY-MM-DD'),
        结案文书签批日期: formatDate(li.closure_audit_datetime, 'YYYY-MM-DD'),
        结案文书送达完成日期: formatDate(li.closure_datetime, 'YYYY-MM-DD'),
        被申请人: li.respondent_name,
        被申请人仲裁员: li.arbitrator2
      }
    })
    json2Excel([{ data: list, sheetname: '案件列表' }], '案件列表')
  }
}

function Main (): ReactElement {
  const dispatch = useDispatch()
  const tableRef = useRef<TableRef>(null)
  const [status, setStatus] = useState<string | undefined>()
  const [dataSource, setDataSource] = useState<CaseSchema[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [searchData, setSearchData] = useState<{[k: string]: any}>({})
  const [params, setParams] = useState<{[k: string]: any}>({})
  useEffect(() => {
    const s = params.status
    if ((typeof s === 'string' || s === undefined) && s !== status) {
      setStatus(s)
    }
  }, [params])
  return (
    <div className={style.container}>
      <Search params={params} setParams={setParams} unused={['assign_datetime']} />
      <div className={style.table}>
        <div className={style['operate-line']}>
          <span className={style['operate-title']}>开庭情况统计</span>
          <Button type='primary' ghost onClick={() => confirmDownload(searchData, total)} >导出excel</Button>
        </div>
        <Table params={params} setParams={setParams} rowKey='orderno' ref={tableRef} columns={getColumn(dispatch)} loading={loading} total={total} dataSource={dataSource} onChange={async d => {
          setSearchData(d)
          await initData(d, setDataSource, setTotal, setLoading)
        }} />
      </div>
    </div>
  )
}

export default Main
